<template>
    <div class="container">
       <div class="app-container">
          <div class="add-btn">
             <el-button type="primary" size="mini" @click="addRole">添加角色</el-button>
          </div>
          <!-- 表格 -->
          <el-table :data="tableData"  style="width: 100%" :cell-style="{borderColor:'#ccc'}"
          :header-cell-style="{borderColor:'#ccc'}" class="table" 
          :header-row-style="{color:'#000'}" v-loading="loading">
          <!-- 第一列 -->
               <el-table-column prop="id" label="序号" width="50" align="center"> </el-table-column>
               <!-- 第二列 -->
               <el-table-column prop="name" label="角色" width="200" align="center"> 
                  <template v-slot="{ row }">
                      <el-input v-if="row.isExit" v-model="row.editRow.name" size="mini"></el-input>
                      <span v-else>{{ row.name }}</span>
                   </template>
                 </el-table-column>
               <!-- 第三列 -->
               <el-table-column prop="state" label="启用" width="200" align="center">
                  <template v-slot="{ row }">
                    <!-- 编辑状态显示开关 -->
                       <template v-if="row.isExit">
                          <el-switch v-model="row.editRow.state" :active-value="1" :inactive-value="0"></el-switch>
                       </template>
                       <!-- 非编辑状态显示文字内容 -->
                       <template v-else>
                         <span v-if="row.state === 1" style="color: green">已启用</span>
                         <span v-else-if="row.state === 0" style="color: orangered;">未启用</span>
                         <span v-else>无状态</span>
                       </template>
                  </template>
               </el-table-column>
               <!-- 第四列 -->
                 <el-table-column prop="description" label="描述" align="center">
                   <template v-slot="{ row }">
                       <el-input v-if="row.isExit" type="textarea" style="width: 300px;" size="mini" v-model="row.editRow.description"></el-input>
                       <span v-else>{{ row.description }}</span>
                   </template>
                 </el-table-column>
               <!-- 第五列 -->
               <el-table-column prop="exit" label="操作" align="center">
                 <template v-slot="{ row }">
                    <template v-if="row.isExit">
                        <el-button type="primary" size="mini" @click="isExitOk(row)">确定</el-button>
                        <el-button  size="mini" @click="isExitNo(row)">取消</el-button>
                    </template>
                    <template v-else>
                      <el-button size="mini" type="text" @click="allocation(row.id)">分配权限</el-button>
                      <el-button size="mini" type="text" @click="isExit(row)">编辑</el-button>
                      <el-button size="mini" type="text" @click="handleDelete(row.id)">删除</el-button>
                    </template>
                  </template>
               </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-row type="flex" justify="end" style=" height: 60px;" align="middle" >
               <el-pagination
                 :page-size="dataPage.pagesize" 
                 :current-page="dataPage.page"
                  background
                  layout="prev, pager, next"
                 :total= "dataPage.total"
                 @current-change="changePage"
                 >
                </el-pagination>
            </el-row>
       </div>
       <Dialog :showDialog = 'showDialog' @changeShow="changeShow" :getRoleList = "getRoleList"></Dialog>
       <el-dialog :visible.sync="ShowPermissionDialog" title="分配权限">
        <!-- default-expand-all :当前选中的节点，  -->
          <el-tree 
             check-on-click-node
             check-strictly
             ref="SeleNode"
            :data="TreeData" 
            :props="{label: 'name'}"
             default-expand-all 
             node-key="id"
            :default-checked-keys="currentRoleList"
            show-checkbox>
        </el-tree>
          <el-row style="width: 100%; height: 50px" type="flex" justify="end" align="middle" slot="footer">
             <el-button type="primary" size="mini" @click="isRoleOk">确定</el-button>
             <el-button size="mini" @click="ShowPermissionDialog = false">取消</el-button>
          </el-row>
       </el-dialog>
    </div>
 </template>
 <script>
 import { gerPermissionListService } from '@/api/permssion';
 import { getRoleService,getDelRoleService , getExitService, getRoleDetailsService, AssignmentService} from '@/api/role'
 import Dialog from '@/views/role/compoents/Dialog.vue'
import { Message, Tree } from 'element-ui';
 import { tranListToTreeData } from '@/utils';
 export default {
    components: { Dialog },
    name: 'Role',
    data(){
      return {
        loading: true,
        showDialog: false,
        tableData: [],
        dataPage:{
          page: 1,  //当前的页码数 ,默认初始化请求第一页
          pagesize: 6,//当前页面需要的条数
          total: 0
        },
        ShowPermissionDialog : false,
        TreeData: [], //树形组件接收的数据
        currentRoleList: [], //选中的结果
        currentRoleId : null //每一行角色数据的ID值
      }
    },
    created(){
      this.getRoleList()
    },
    methods: {
      // 获取数据，渲染页面
    async getRoleList() {
       const res = await getRoleService(this.dataPage)
       this.loading = false
       this.tableData = res.rows
       this.dataPage.total = res.total
      //  响应式：根据已有的属性，数据变化，试图更新，如果我们用forEach方法添加一个动态属性那么需要用到 this.$set方法
          this.tableData.forEach((item) => {
             this.$set(item, 'isExit' , false)
             this.$set(item, 'editRow' , {
               name: item.name,
               description: item.description,
               state: item.state
             })
          }
        )
      },
      // 分页逻辑
      changePage(newPage){
        this.dataPage.page = newPage
        this.getRoleList()
      },
      // 删除逻辑
      async handleDelete(id){
        await this.$confirm('确认删除此条数据么？？', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
       await getDelRoleService(id)
       Message({type: 'success' , message : '删除成功'})
       this.getRoleList()
      },
      // 添加逻辑
      addRole(){
        this.showDialog = true
      },
      changeShow() {
         this.showDialog = false
      },
      // 编辑逻辑
      isExit(row) {
        // console.log(row);
          row.isExit = true
          row.editRow.name = row.name,
          row.editRow.description = row.description,
          row.editRow.state = row.state
      },
      // 编辑完成后点击确定
      async isExitOk(row) {
        // 如果 角色和描述都有值的情况下
        if(row.editRow.description && row.editRow.name){
         await getExitService({...row.editRow, id: row.id}) //发送请求
        //  将缓存中修改后的值 赋值 给 最外层的新值
         row.name = row.editRow.name,
         row.description = row.editRow.description
         row.state = row.editRow.state
         this.loading = false
         this.getRoleList() //重新渲染页面
         row.isExit = false //退出编辑模式
         Message({ type:'success' , message: '更新成功' })
        }else {
          Message({type: 'warning' , message: '角色和描述都不能为空'} )
        }
      },
      // 取消编辑
      isExitNo(row) {
         row.isExit = false
      },
      // 给角色分配权限页面
      async allocation(id){
        // 将id记录下来
        this.currentRoleId = id
        // 调用获取角色详情的接口
        const { permIds } = await getRoleDetailsService(id)
        // 将permIds记录下来
        this.currentRoleList = permIds
        this.TreeData = tranListToTreeData(await gerPermissionListService(), 0)
        // 所有逻辑都执行完毕再打开弹窗
        this.ShowPermissionDialog = true
      },
      // 点击确定发送请求，关闭分配权限的弹层
      async isRoleOk(){
         await AssignmentService({
           id: this.currentRoleId,
           permIds: this.$refs.SeleNode.getCheckedKeys()
         })
        //  提示消息
         Message({ type: 'success', message: '分配权限成功' })
         //  关闭弹层
         this.ShowPermissionDialog = false
      },
    }
 }
 </script>
 
 <style scoped>
 .add-btn{
   padding: 20px 0  20px 20px;
 }
 .table{
   border-bottom: 1px solid #ccc;
 }
 </style>